<template>
  <div class="term-root">
    <div class="term-board">
      <div class="term-log">{{logStr}}</div>
      <div class="term-input-line">
        <span class="term-input-pre">></span>
        <input type="text" class="term-input" v-model="cmd" @keypress.enter="exec">
      </div>

    </div>

  </div>
</template>

<script>
import { socketUrl } from '../util'

export default {
  name: 'Term',
  data() {
    return {
      logStr: '',
      ws: null,
      cmd: '',
    }
  },
  methods: {
    init() {
      this.ws = new WebSocket(socketUrl)
      // Connection opened
      this.ws.addEventListener('open', (event) => {
          this.ws.send(' ');
      });

      // Listen for messages
      this.ws.addEventListener('message', (event) => {
        this.onRecv(event.data)
        // console.log('Message from server ', event.data);
      });
    },
    onRecv(data) {
      this.logStr += data
    },
    exec() {
      if (this.logStr[this.logStr.length -1] != '\n') {
        this.logStr += `\n`
      }
      this.logStr += `> ${this.cmd}\n`
      this.ws.send(this.cmd);
      this.cmd = ''
    }

  },
  mounted() {
    this.init()
    console.warn('mount')
  }
}
</script>

<style scoped>
.term-root {
  font-family:'Courier New', Courier, monospace
}
.term-board {
  width: 100%;
  height: 100vh;
  padding: 14px;
  background-color: #000;
  color: #fff;
}
.term-log {
  white-space:pre-wrap;
}
.term-input {
  background: transparent;
  color: #fff;
  border: none;
  outline: none;
  font-family:inherit;
  font-size: inherit;
}
</style>
